﻿using System.Collections.Generic;
using System.Linq;
using Omu.Awesome.Core;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.Data
{
    public class Repo<T> : IRepo<T> where T : Entity, new()
    {
        public int Insert(T o)
        {
            o.Id = ++Db.Sequence;
            Db.Table<T>().Add(o);
            return o.Id;
        }

        public void Delete(int id)
        {
            Db.Table<T>().Remove(Get(id));
        }

        public void Update(T o)
        {
            Delete(o.Id);
            Db.Table<T>().Add(o);
        }

        public T Get(int id)
        {
            return Db.Table<T>().Where(o => o.Id == id).SingleOrDefault();
        }

        public IEnumerable<T> GetAll()
        {
            return Db.Table<T>().OrderByDescending(o => o.Id);
        }

        public int Count()
        {
            return Db.Table<T>().Count;
        }

        public IEnumerable<T> GetPage(int page, int pageSize)
        {
            return Db.Table<T>().OrderByDescending(o => o.Id).Skip((page-1) * pageSize).Take(pageSize);
        }

        public IPageable<T> GetPageable(int page, int pageSize)
        {
            return new Pageable<T>
                       {
                           Page = GetPage(page, pageSize),
                           PageCount = GetPageCount(pageSize, Count() ),
                           PageIndex = page
                       };
        }

        static int GetPageCount(int pageSize, int count)
        {
            var pages = count / pageSize;
            if (count % pageSize > 0) pages++;
            return pages;
        }
    }
}